# -*- encoding: utf-8 -*-

import utime as time
import usocket
import _thread  


def tcpsend(s):
    while True:
        try:
            s.send("heartbeatbuf")
            time.sleep(5)
        except OSError:
            print('TCP OSError send')
            break
        except:
            break

def tcprecv(s):
    while True:
        try:
            recvdata = s.recv(255)
        except OSError:
            print('TCP OSError recv')
            break
        except:
            break
        if len(recvdata) > 0:
            print(f'recv: {recvdata}')
        time.sleep(1)

def do_connect(host,port):
    global sock
    sock = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)
    try :         
        sock.connect((host, port))
    except :
        pass
    return sock

def update3(host,port):
    """
    更新并保持TCP连接活跃
    
    参数:
        host (str): 目标主机地址
        port (int): 目标端口号
    
    功能:
        1. 发送当前时间戳到服务器
        2. 若发送失败则自动重连
        3. 重连间隔为3秒
    
    异常处理:
        捕获所有socket异常并自动重连
    """
    global sock
    try :
        msg = time.localtime()
        print(f'send: {msg}')
        sock.send(str(msg))
    except OSError as e:
        print('OSError: {}'.format(e))
        time.sleep(3)
        sock.close()
        sock = do_connect(host, port)   
def demo(host, port):    
    sock = do_connect(host, port)
    _thread.start_new_thread(tcprecv, (sock,))  

